<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { $t } from '@/locales';
import { formatDateAgo } from '@/utils/common';
import { ElSkeleton, ElButton } from 'element-plus';

const authStore = useAuthStore();
const userInfo = computed(() => authStore.userInfo);
const loading = ref(true);
const error = ref(false);

onMounted(async () => {
  loading.value = true;
  error.value = false;
  
  try {
    if (!userInfo.value.userId) {
      await authStore.getUserInfo();
    }
  } catch (e) {
    console.error('Failed to load user info:', e);
    error.value = true;
  } finally {
    loading.value = false;
  }
});

const avatarUrl = computed(() => {
  return userInfo.value.userImages || 'http://127.0.0.1:9000/image-bucket/20250514/fbee6c07a7d24746884456b56b6a21bfd1ee7e8c-5af4-462a-bf59-e58a053dba21.jpg';
});
</script>

<template>
  <div class="user-center-container">
    <div class="user-center">
      <h2 class="title">{{ $t('page.userCenter.title') }}</h2>
      
      <div v-if="loading" class="loading-state">
        <ElSkeleton :rows="5" animated />
      </div>
      
      <div v-else-if="error" class="error-state">
        <div class="error-message">
          {{ $t('common.message.error') }}
        </div>
        <ElButton @click="authStore.getUserInfo()">
          {{ $t('common.button.retry') }}
        </ElButton>
      </div>
      
      <template v-else>
        <el-card class="user-card">
          <div class="user-info">
            <el-avatar :size="80" :src="avatarUrl"></el-avatar>
            <div class="user-details">
              <h3>{{ userInfo.userName }}</h3>
              <p>ID: {{ userInfo.userId }}</p>
              <div class="user-roles">
                <el-tag v-for="role in userInfo.roles" :key="role" size="small">
                  {{ role }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </template>
    </div>
  </div>
</template>

<style scoped>
.user-center-container {
  padding: 20px;
}

.user-center {
  max-width: 800px;
  margin: 0 auto;
}

.title {
  margin-bottom: 20px;
  font-size: 24px;
}

.user-card {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 20px;
}

.user-details h3 {
  margin: 0 0 8px 0;
}

.user-details p {
  margin: 0 0 12px 0;
  color: #909399;
}

.user-roles {
  display: flex;
  gap: 8px;
}

.loading-state,
.error-state {
  padding: 40px;
  text-align: center;
}

.error-message {
  margin-bottom: 16px;
  color: #f56c6c;
}
</style>
